package cn.edu.tju.elm.service.impl;

import cn.edu.tju.core.model.User;
import cn.edu.tju.elm.dto.CartItemDto;
import cn.edu.tju.elm.model.Cart;
import cn.edu.tju.elm.model.Food;
import cn.edu.tju.elm.repository.CartRepository;
import cn.edu.tju.elm.repository.FoodRepository;
import cn.edu.tju.elm.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.server.ResponseStatusException;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class CartServiceImpl implements CartService {

    @Autowired private CartRepository cartRepository;
    @Autowired private FoodRepository foodRepository;

    @Override
    @Transactional
    public Cart addOrUpdateCartItem(CartItemDto cartItemDto, User customer) {
        
        if (cartItemDto.getFood() == null || cartItemDto.getFood().getId() == null) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "请求体中必须包含有效的 food.id");
        }
        Long foodId = cartItemDto.getFood().getId();

        // 1. 验证要添加的菜品是否存在
        Food food = foodRepository.findById(foodId)
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "菜品不存在"));

        // 2. 检查这个菜品是否已在用户的购物车中
        Optional<Cart> existingCartItemOpt = cartRepository.findByCustomerIdAndFoodId(customer.getId(), food.getId());

        Cart cartItemToSave;
        if (existingCartItemOpt.isPresent()) {
            // 3a. 如果已存在，则更新数量
            cartItemToSave = existingCartItemOpt.get();
            int newQuantity = cartItemToSave.getQuantity() + cartItemDto.getQuantity();
            cartItemToSave.setQuantity(newQuantity);
        } else {
            // 3b. 如果不存在，则创建新的购物车条目
            cartItemToSave = new Cart();
            cartItemToSave.setCustomer(customer);
            cartItemToSave.setFood(food);
            cartItemToSave.setBusiness(food.getBusiness()); // 从菜品信息中获取商家信息
            cartItemToSave.setQuantity(cartItemDto.getQuantity());
            // 设置审计字段 (creator, createTime等)
            cartItemToSave.setCreator(customer.getId());
            cartItemToSave.setCreateTime(LocalDateTime.now());
            cartItemToSave.setDeleted(false);
        }
        
        // 4. 设置更新信息并保存
        cartItemToSave.setUpdater(customer.getId());
        cartItemToSave.setUpdateTime(LocalDateTime.now());
        
        return cartRepository.save(cartItemToSave);
    }

    @Override
    public List<Cart> getCartItemsByUser(User customer) {
        return cartRepository.findByCustomerId(customer.getId());
    }

    @Override
    public List<Cart> getCartItemsByUserAndBusiness(User customer, Long businessId) {
        return cartRepository.findByCustomerIdAndBusinessId(customer.getId(), businessId);
    }

    @Override
    @Transactional
    public Cart updateCartItemQuantity(CartItemDto cartItemDto, User customer) {
        
        if (cartItemDto.getFood() == null || cartItemDto.getFood().getId() == null) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "请求体中必须包含有效的 food.id");
        }
        Long foodId = cartItemDto.getFood().getId();
        
        // 查找购物车中的项目
        Cart cartItem = cartRepository.findByCustomerIdAndFoodId(customer.getId(), foodId)
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "购物车中不存在该商品"));
        
        // 更新数量
        cartItem.setQuantity(cartItemDto.getQuantity());
        cartItem.setUpdater(customer.getId());
        cartItem.setUpdateTime(LocalDateTime.now());
        
        return cartRepository.save(cartItem);
    }

    @Override
    @Transactional
    public void deleteCartItem(Long foodId, User customer) {
        // 查找购物车中的项目
        Cart cartItem = cartRepository.findByCustomerIdAndFoodId(customer.getId(), foodId)
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "购物车中不存在该商品"));
        
        // 删除购物车项
        cartRepository.delete(cartItem);
    }
}